#pragma once
#include <iostream>
#include <strings.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

#define BACKLOG 5

class TcpServer {
    private:
        TcpServer(u_int16_t _port)
            :port(_port)
            ,listen_sock(-1)
        {}
        TcpServer(const TcpServer &) {};
        static TcpServer *svr;
    public:
        static TcpServer* getInstance(int _port) {
            static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
            if (svr == nullptr) {
                pthread_mutex_lock(&lock);
                if (svr == nullptr) {
                    svr = new TcpServer(_port);
                    svr->Init();
                }
                pthread_mutex_unlock(&lock);
            }
            return svr;
        }
        void Init() {
            Socket();
            Bind();
            Listen();
            LOG(INFO, "tcp_server init ....... success");
        }
        void Socket() {
            listen_sock = socket(AF_INET, SOCK_STREAM, 0);
            if (listen_sock < 0) {
                LOG(FATAL, "socket error");
                exit(2);
            }
            int opt = 1;
            if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(opt)) < 0) {
                LOG(ERROR, "setsockopt");
                exit(-1);
            }
            LOG(INFO, "create socket ...... success"); 
        }
        int Sock() {
            return listen_sock;
        }
        void Bind() {
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            socklen_t len = sizeof(local);
            if (bind(listen_sock, (struct sockaddr*)&local, sizeof(local)) < 0) {
                LOG(FATAL, "bind socket error");
                exit(3);
            }
            LOG(INFO, "bind socket ...... success");
        }
        void Listen() {
            if (listen(listen_sock, BACKLOG) < 0) {
                LOG(FATAL, "listen socket error");
                exit(4);
            }
            LOG(INFO, "listen socket ...... success");
        }
        ~TcpServer() {
            if (listen_sock > 0) {
                close(listen_sock);
            }
        }
    private:
        u_int16_t port;
        int listen_sock;    
};


TcpServer* TcpServer::svr = nullptr;